from datetime import date, timedelta

from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import GoodsVisitCount
from meiduo_admin.home.home_serializer import GoodCategorySerializer
from user.models import User


class UserTotalCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 1,获取用户总数
        # count = User.objects.filter(is_staff=False).count()
        count = User.objects.count()

        # 2,返回响应
        return Response({
            "count": count
        })


class UserDayIncreaseCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 1,查询日增用户数量
        count = User.objects.filter(date_joined__gte=date.today()).count()

        # 2,返回响应
        return Response({
            "count": count
        })


class UserDayActiveCountView(APIView):
    def get(self, request):
        # 1,查询日活用户数量
        count = User.objects.filter(last_login__gte=date.today()).count()

        # 2,返回响应
        return Response({
            "count": count
        })


class UserDayOrdersCountView(APIView):
    def get(self, request):
        # 1,查询日下单用户
        count = User.objects.filter(orderinfo__create_time__gte=date.today()).count()

        # 2,返回响应
        return Response({
            "count": count
        })


class UserMonthIncrementCountView(APIView):
    def get(self, request):
        old_date = date.today() - timedelta(days=30)
        count_list = []
        for i in range(1, 31):
            current_date = old_date + timedelta(days=i)
            next_date = old_date + timedelta(days=i + 1)
            count = User.objects.filter(date_joined__gte=current_date, date_joined__lt=next_date).count()
            count_list.append({
                'count': count,
                'date': current_date
            })
        return Response(count_list)


class GoodCategoryVisitCountView(ListAPIView):
    queryset = GoodsVisitCount.objects.all()
    serializer_class = GoodCategorySerializer

    def get_queryset(self):
        return GoodsVisitCount.objects.filter(date=date.today()).all()

    # def get(self, request):
        # 方式一:
        # 1.接收数据
        # today = date.today()
        # 2.查询访问量
        # categories = GoodsVisitCount.objects.filter(date=today).all()
        # 获取查询集
        # categories = self.get_queryset()
        # 创建序列化器对象
        # serializer = self.get_serializer(instance=categories,many=True)
        # 3.拼接数据
        # category_list = []
        # for category in categories:
        #     category_list.append({
        #         "category":category.category.name,
        #         "count":category.count
        #     })
        # 4.返回响应
        # return Response(serializer.data)

        # 方式二:
        # return self.list(request)
